<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/7/11 14:20
 */

namespace App\Transformers;

use App\Models\MedicalDispose;
use App\Models\MedicalHpiSub;
use App\Models\MedicalRecord;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use League\Fractal\TransformerAbstract;

class PreviousFollowWithPatientTransformer extends TransformerAbstract
{
    protected $availableIncludes = ['previousSub', 'previousMedication'];

    /**
     * 上次病历
     * @var \App\Models\MedicalRecord|null
     */
    protected $record;

    /**
     * 当前请求
     * @var \Illuminate\Http\Request
     */
    protected $request;

    /**
     * 构造器
     * PreviousFollowWithPatientTransformer constructor.
     * @param \Illuminate\Http\Request $request
     * @param null                     $patient_id
     */
    public function __construct(Request $request, $patient_id = null)
    {
        $this->request = $request;

        if (empty($patient_id)) {
            $patient_id = $request->input('patient_id');
        }

        $this->record = (new MedicalRecord())->select(['id', 'visit_type', 'is_western'])->previousWithPatient($patient_id)->first();
    }

    public function transform($patient) { return []; }

    /**
     * 获取上一次随诊或首诊的现病史组
     * @param \App\Models\Patient $patient
     * @return \League\Fractal\Resource\Collection
     */
    public function includePreviousSub($patient)
    {
        $previousSub = [];

        if ($this->record instanceof MedicalRecord) {
            $previousSub = MedicalHpiSub::where(['record_id' => $this->record->id])->get();
        }

        return $this->collection($previousSub, new HpiSubTransformer());
    }

    /**
     * 获取上一次随诊或首诊的处理 中西医 用药
     * @param \App\Models\Patient $patient
     * @return \League\Fractal\Resource\Item
     */
    public function includePreviousMedication($patient)
    {
        $medication = [];
        $select = ['medication'];
        if ($this->record instanceof MedicalRecord) {

            if ($this->record->isChinese()) {
                $select[] = 'cn_medication';
            }

            $medication = MedicalDispose::select($select)->where(['record_id' => $this->record->id])->first();
        }

        return $this->item($medication, function ($medication) use ($select) {
            if (empty($medication)) {
                return ['medication'=>'', 'cn_medication'=>''];
            }

            $back = [
                'medication'=> $medication->medication
            ];
            if (in_array('cn_medication', $select)) {
                $back['cn_medication'] = $medication->cn_medication;
            }

            return $back;
        });
    }
}